import * as THREE from 'three'
import { Mesh, MeshBasicMaterial } from 'three'
import createApp from '../../core'

function createPlaneGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)
  camera.position.set(0, 0, 50)
  camera.lookAt(scene.position)

  const geometry = new THREE.PlaneGeometry(50, 50)
  const material = new MeshBasicMaterial({ side: THREE.DoubleSide, color: 0xff0000 })
  const mesh1 = new Mesh(geometry, material)
  mesh1.material.polygonOffset = true
  mesh1.material.polygonOffsetUnits = 44
  scene.add(mesh1)



  const mesh = createPlaneFromGeometry()
  scene.add(mesh)

  const bufferMesh = createPlaneFromBufferGeometry()
  bufferMesh.position.x = 30
  scene.add(bufferMesh)

  update((time: number) => {
    // const angle = time / 1000
    // mesh.rotation.set(angle, angle, 0)

    // bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'width', 0, 30).onChange(updateMeshs)
  gui.add(data, 'height', 0, 30).onChange(updateMeshs)
  gui.add(data, 'widthSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'heightSegments', 1, 30, 1).onChange(updateMeshs)
}

const data = {
  width: 10,
  height: 20,
  widthSegments: 1,
  heightSegments: 1
}

function createPlaneFromGeometry () {
  const { width, height, widthSegments, heightSegments } = data
  const geometry = new THREE.PlaneGeometry(width, height, widthSegments, heightSegments)
  const material = new MeshBasicMaterial({ side: THREE.DoubleSide })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function createPlaneFromBufferGeometry () {
  const { width, height, widthSegments, heightSegments } = data
  const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments)
  const material = new MeshBasicMaterial({ side: THREE.DoubleSide })
  const mesh = new Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { width, height, widthSegments, heightSegments } = data
  const geometry = new THREE.PlaneBufferGeometry(width, height, widthSegments, heightSegments)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createPlaneGeometry
}

